import NEV from "./config.js"
import vue from '@/main.js'

// import logout from "@/utils/logout.js"


const defauls = {
	method: "POST",
	loading: true
}

// 全局请求封装
export default (path, data = {}, config ,params = {}) => {
	if(config == null){
		config = defauls
	}
	let paramsStr = ""
	if(Object.keys(params).length) {
		paramsStr = Object.keys(params).reduce((pre, cur) => {
			pre += (cur + "=" + String(params[cur]) + "&")
			return pre
		}, "")
	}
	console.log("paramsStr=>",paramsStr)	
	// const lang  = uni.getStorageSync('lang') ? uni.getStorageSync('lang') : "en_US";
	const OaAuth = uni.getStorageSync("OaAuth") || '';
	return new Promise((resolve, reject) => {
		uni.request({
			header: {
				"Content-Type": "application/json",
				"OaAuth": OaAuth
				// "lang": lang
			},
			url: NEV.ROOT_URL + path + "?" + paramsStr ,
			method: config.method,
			data,
			success(response) {
				if(response.data.code == 200 || response.data.code == 204){
					resolve(response.data);
				}else{
					if(response.data.code == 401){
						uni.redirectTo({
						  url: "/pages/login/login"
						});
					}else{
						setTimeout(()=>{
							uni.showToast({
								icon: "none",
								duration: 2000,   
								title: response.data.message
							});
						},700)
					}
				}
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);  
			},
			complete() {
				setTimeout(() => {
						uni.hideLoading() 
				}, 1500)
			}
		});
	});
};
